package com.zhb.zhbojbackendjudgeservice.rabbitmq;

import com.rabbitmq.client.Channel;
import com.zhb.zhbojbackendjudgeservice.judge.JudgeService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.amqp.core.Message;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class MyMessageConsumer {

    @Resource
    private JudgeService judgeService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    // 设置消息的最大重试次数为3，当超过3次没被消费者消费就送往死信交换机，死信交换机再传递给死信队列
    public static final int MAX_RETRIES = 2;

    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {"code_queue"}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel,
                               @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                               @Header(name = "retry-count", required = false) Integer retryCount,
                               Message rawMessage) {
        // 初始化重试次数
        retryCount = (retryCount == null) ? 0 : retryCount;
        log.info("当前重试次数: {}", retryCount);

        try {
            // 模拟处理失败,触发重试，达到重试次数将消息发送给死信队列
//            if (retryCount < 3) {
//                throw new RuntimeException("模拟处理失败，触发重试");
//            }
            judgeService.doJudge(Long.parseLong(message));
            channel.basicAck(deliveryTag, false);

        } catch (Exception e) {
            if (retryCount < MAX_RETRIES) {
                log.info("重试次数 {}，重新发送消息", retryCount);
                // 发送时增加重试次数
                Integer finalRetryCount = retryCount;
                rabbitTemplate.convertAndSend(
                        InitRabbitMqBean.EXCHANGE_NAME,
                        "my_routingKey",
                        message,
                        m -> {
                            m.getMessageProperties().setHeader("retry-count", finalRetryCount + 1);
                            return m;
                        });
            } else {
                log.info("达到最大重试次数，转入死信队列");
                rabbitTemplate.convertAndSend(
                        InitRabbitMqBean.DEAD_EXANGE_NAME,
                        "dead_routingKey",
                        message);
            }
            channel.basicNack(deliveryTag, false, false);
        }
    }

}
